package com.awifi.dao.impl;

import com.awifi.dao.AccountDao;
import com.awifi.entity.Account;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Account findAccountByName(String name) {
        String sql = "select * from account where username=?";
        List<Account> accounts = jdbcTemplate.query(sql,new AccountRowMapper(),name);
        return accounts.get(0);
    }

    public List<Account> findAllAccount() {
        String sql = "select * from account";
        List<Account> accounts = jdbcTemplate.query(sql,new AccountRowMapper());
        return accounts;
    }

    public void save(Account account) {
        String sql = "insert into account(username,password) values(?,?)";
        jdbcTemplate.update(sql,account.getUsername(),account.getMoney());
    }

    public void delete(Account account) {
        String sql = "delete from account where username=?";
        jdbcTemplate.update(sql,account.getUsername());
    }

    public void update(Account account) {
        String sql = "update account set username=?,money=? where id=?";
        jdbcTemplate.update(sql,account.getUsername(),account.getMoney(),account.getId());
    }

    class AccountRowMapper implements RowMapper<Account> {

        public Account mapRow(ResultSet resultSet, int i) throws SQLException {
            Account account = new Account();
            account.setId(resultSet.getInt("id"));
            account.setUsername(resultSet.getString("username"));
            account.setMoney(resultSet.getFloat("money"));
            return account;
        }
    }
}
